﻿using System.Web;
using System.Xml;
using System.Data;
using System.Collections;

using System.Collections.Generic;
using System.IO;
using TRPOP.Common;

namespace TRPOP.CMS.Model
{
    /// <summary>
    /// 当前系统的配置参数信息
    /// </summary>
    public static class SYSConfig
    {
        /// <summary>
        /// CMS 管理目录 的相对路径信息
        /// 例如: /CMS
        /// </summary>
        private static string AdminRoot = SystemInfoHelper.getSystemInfo().CMSRoot + SystemInfoHelper.getSystemInfo().AdminFolderName;

        #region 基本的操作方法

        /// <summary>
        /// 根据变量key 变量类型 获取该变量的信息集合
        /// </summary>
        /// <param name="strVar">变量key</param>
        /// <param name="strParamTypeKey">变量类型key</param>
        /// <returns></returns>
        public static ArrayList GetVarValue(string strVar, string strParamTypeKey)
        {
            string strPath = Common.Util.GetMapPath(AdminRoot + "/config/" + strParamTypeKey + ".config");
            if (!File.Exists(strPath))
            {
                XmlDocument oXmlDoc = new XmlDocument();
                //xml类型说明
                XmlNode oxmlnode = oXmlDoc.CreateXmlDeclaration("1.0", "utf-8", null);
                oXmlDoc.AppendChild(oxmlnode);
                //根节点
                XmlElement oxmlParamType = oXmlDoc.CreateElement("", strParamTypeKey, "");
                XmlText oxmlParamTypeText = oXmlDoc.CreateTextNode("");
                oxmlParamType.AppendChild(oxmlParamTypeText);
                oXmlDoc.AppendChild(oxmlParamType);


                //添加items结点
                XmlElement oxmlItems = oXmlDoc.CreateElement("", "items", "");
                XmlText oxmltext = oXmlDoc.CreateTextNode("");
                oxmlItems.AppendChild(oxmltext);
                oxmlParamType.AppendChild(oxmlItems);
                oXmlDoc.Save(strPath);
            }
            if (File.Exists(strPath))
            {
                return ConfigManage.GetValue(strVar, strPath);
            }
            return null;
        }

        /// <summary>
        /// 根据 某 变量属性集合、属性值 集合来保存某变量信息 
        /// </summary>
        /// <param name="strAttribute">变量属性集合</param>
        /// <param name="strValue">属性值集合</param>
        /// <param name="strParamTypeKey">变量类型</param>
        /// <returns></returns>
        public static bool SaveVarValue(ArrayList strAttribute, ArrayList strValue, string strParamTypeKey)
        {
            string strPath = Common.Util.GetMapPath(AdminRoot + "/config/" + strParamTypeKey + ".config");
            if (!File.Exists(strPath))
            {
                return false;
            }
            return ConfigManage.SaveConfigValue(strAttribute, strValue, strPath);
        }

        /// <summary>
        /// 根据key删除结点
        /// </summary>
        /// <param name="ArrayKey"></param>
        /// <param name="strParamTypeKey"></param>
        /// <returns></returns>
        public static bool DelConfigValue(ArrayList ArrayKey, string strParamTypeKey)
        {
            string strPath = Common.Util.GetMapPath(AdminRoot + "/config/" + strParamTypeKey + ".config");
            return ConfigManage.DelConfigValue(ArrayKey, strPath);
        }

        /// <summary>
        ///  获取某结点类型下的所有变量集合
        /// </summary>
        /// <param name="strParamTypeKey">变量类型</param>
        /// <param name="NodeListPath">结点路径</param>
        /// <returns></returns>
        public static DataTable GetDataSource(string strParamTypeKey, string NodeListPath)
        {
            string strPath = Common.Util.GetMapPath(AdminRoot + "/config/" + strParamTypeKey + ".config");
            if (!File.Exists(strPath))
            {
                GetVarValue("test", strParamTypeKey);
                return null;
            }
            return ConfigManage.GetDataSource(strPath, NodeListPath);
        }

        /// <summary>
        /// 根据文件名，数据变量名 获取值
        /// </summary>
        /// <param name="strVar"></param>
        /// <param name="strFileName"></param>
        /// <returns></returns>
        public static string GetVarValueFromConfig(string strVar, string strFileName)
        {
            DataTable tableTemp = GetDataSource(strFileName, "//items");
            if (tableTemp != null && tableTemp.Rows.Count > 0)
            {
                foreach (DataRow TempRow in tableTemp.Rows)
                {
                    if (TempRow.Table.Columns.Contains("VarKey") && TempRow["VarKey"].ToString().ToLower().Trim() == strVar.Trim().ToLower())
                    {
                        return TempRow["VarValue"].ToString();
                    }
                }
            }
            return string.Empty;
        }

        #endregion

        #region 是否开启缓存机制
        static bool m_Cache_Enable = true;
        /// <summary>
        /// 是否开启缓存
        /// </summary>
        public static bool Cache_Enable
        {
            get
            {
                return m_Cache_Enable;
            }
            set
            {
                m_Cache_Enable = value;
            }
        }
        #endregion

        #region 系统变量

        #region 系统基本变量
        /// <summary>
        /// 网站域名
        /// </summary>
        public static string SystemVar_SiteURL
        {
            get
            {
                return SystemVarInfoHelper.GetSystemVarbyKey("SITE_URL"); //(GetVarValueForCMSVar("SITE_URL")); 
            }
        }

        /// <summary>
        /// 网站首页文件名
        /// </summary>
        public static string SystemVar_IndexPageName
        {
            get
            {
                return SystemVarInfoHelper.GetSystemVarbyKey("Index_Name");//(GetVarValueForCMSVar("Index_Name")); 
            }
        }

        /// <summary>
        /// 网站名称
        /// </summary>
        public static string SystemVar_SiteName
        {
            get
            {
                return SystemVarInfoHelper.GetSystemVarbyKey("SITE_NAME");//(GetVarValueForCMSVar("SITE_NAME")); 
            }
        }

        /// <summary>
        /// 缓存时间
        /// </summary>
        public static double SystemVar_CahceSeconds
        {
            get
            {
                double dbCahceSeconds = SystemVarInfoHelper.GetSystemVarbyKey("CahceSeconds").ToDouble();
                if (dbCahceSeconds <= 0)
                    return 60 * 10;
                else
                    return dbCahceSeconds;
            }
        }

        /// <summary>
        /// 模板地址
        /// </summary>
        public static string SystemVar_Templatepath
        {
            get
            {
                string strTemplate = SystemVarInfoHelper.GetSystemVarbyKey("templatepath"); // GetVarValueForCMSVar("admin_templatepath");

                if (strTemplate.IsEmpty())
                    return @"/templates";
                else
                    return strTemplate;
            }
        }

        /// <summary>
        /// 信息统计页面 
        /// </summary>
        public static string SystemVar_InfoClickSubmitURL
        {
            get
            {
                return SystemVarInfoHelper.GetSystemVarbyKey("InfoClickSubmit");//(GetVarValueForCMSVar("InfoClickSubmit"));
            }
        }

        /// <summary>
        /// 自动分页单页内容长度
        /// </summary>
        public static int SystemVar_ContentPageLength
        {
            get
            {
                return SystemVarInfoHelper.GetSystemVarbyKey("ContentPageLength").ToInt();
            }
        }

        /// <summary>
        /// 请n页静态
        /// </summary>
        public static int SystemVar_listPageCount
        {
            get
            {
                return SystemVarInfoHelper.GetSystemVarbyKey("listPageCount").ToInt();
            }
        }

        /// <summary>
        /// 列表页动态访问地址 
        /// </summary>
        public static string SystemVar_listAutoPage
        {
            get
            {
                return SystemVarInfoHelper.GetSystemVarbyKey("listAutoPage"); //GetVarValueForCMSVar("listAutoPage");
            }
        }

        /// <summary>
        /// 内容页动态访问地址 
        /// </summary>
        public static string SystemVar_ContentAutoPage
        {
            get
            {
                return SystemVarInfoHelper.GetSystemVarbyKey("ContentAutoPage"); //GetVarValueForCMSVar("ContentAutoPage");
            }
        }

        /// <summary>
        /// 通用页面存放址地
        /// </summary>
        public static string SystemVar_NodeIndexPage
        {
            get
            {
                return SystemVarInfoHelper.GetSystemVarbyKey("NodeIndexPage"); //GetVarValueForCMSVar("NodeIndexPage"); 
            }
        }

        /// <summary>
        /// 搜索页URL
        /// </summary>
        public static string SystemVar_PageSearchURL
        {
            get
            {
                return SystemVarInfoHelper.GetSystemVarbyKey("PageSearchURL"); //= GetVarValueForCMSVar("PageSearchURL");
            }
        }

        /// <summary>
        /// 搜索模板路径
        /// </summary>
        public static string SystemVar_PageSearchTemplate
        {
            get
            {
                return SystemVarInfoHelper.GetSystemVarbyKey("PageSearchTemplate"); //= GetVarValueForCMSVar("PageSearchTemplate");
            }
        }

        /// <summary>
        /// 页面提示模板路径
        /// </summary>
        public static string SystemVar_PagePromotTemplate
        {
            get
            {
                return SystemVarInfoHelper.GetSystemVarbyKey("PagePromotTemplate"); //= GetVarValueForCMSVar("PagePromotTemplate");
            }
        }

        /// <summary>
        /// 搜索模板 关键字 input Name
        /// </summary>
        public static string SystemVar_SearchFormInputName
        {
            get
            {
                return SystemVarInfoHelper.GetSystemVarbyKey("SearchFormInputName"); //= GetVarValueForCMSVar("SearchFormInputName");
            }
        }
        #endregion

        #region 资源发布、内容发布 变量
        /// <summary>
        /// 默认资源发布点
        /// </summary>
        public static string SystemVar_DefaultResourcePSN
        {
            get
            {

                string strReturn = SystemVarInfoHelper.GetSystemVarbyKey("DefaultResourcePSN");//(GetVarValueForCMSVar("DefaultResourcePSN"));

                if (string.IsNullOrEmpty(strReturn))
                    strReturn = "{PSN:1}";
                return strReturn;
            }
        }

        /// <summary>
        /// 默认资源发布URL
        /// </summary>
        public static string SystemVar_DefaultResourcePSNURL
        {
            get
            {
                string strReturn = SystemVarInfoHelper.GetSystemVarbyKey("DefaultResourcePSNURL");//(GetVarValueForCMSVar("DefaultResourcePSNURL"));

                if (string.IsNullOrEmpty(strReturn))
                    strReturn = "{PSN-URL:1}";
                return strReturn;
            }
        }

        /// <summary>
        /// 默认内容发布点
        /// </summary>
        public static string SystemVar_DefaultContentPSN
        {
            get
            {
                string strReturn = SystemVarInfoHelper.GetSystemVarbyKey("DefaultContentPSN");//(GetVarValueForCMSVar("DefaultContentPSN"));

                if (string.IsNullOrEmpty(strReturn))
                    strReturn = "{PSN:1}/html";
                return strReturn;
            }
        }

        /// <summary>
        /// 默认内容发布URL
        /// </summary>
        public static string SystemVar_DefaultContentPSNURL
        {
            get
            {
                string strReturn = SystemVarInfoHelper.GetSystemVarbyKey("DefaultContentPSNURL");//(GetVarValueForCMSVar("DefaultContentPSNURL"));

                if (string.IsNullOrEmpty(strReturn))
                    strReturn = "{PSN-URL:1}/html";
                return strReturn;
            }
        }
        #endregion

        #region 发布管理相关参数
        /// <summary>
        /// 发布管理页标题长度
        /// </summary>
        public static int SystemVar_ListTitleLength
        {
            get
            {
                int inGetvalue = SystemVarInfoHelper.GetSystemVarbyKey("list_titlelength").ToInt();//GetVarValueForCMSVar("list_titlelength")
                return inGetvalue > 0 ? inGetvalue : 10;
            }

        }

        /// <summary>
        /// 发布管理单页显示记录
        /// </summary>
        public static int SystemVar_AdminContentPageNum
        {
            get
            {
                int inGetvalue = SystemVarInfoHelper.GetSystemVarbyKey("adminContentPageNum").ToInt();//GetVarValueForCMSVar("adminContentPageNum")
                return inGetvalue > 0 ? inGetvalue : 10;
            }
        }

        /// <summary>
        /// 发布管理单页内容显示最大值
        /// </summary>
        public static int SystemVar_PubPageListMax
        {
            get
            {
                int inGetvalue = SystemVarInfoHelper.GetSystemVarbyKey("PubPageListMax").ToInt();//GetVarValueForCMSVar("PubPageListMax")
                return inGetvalue > 0 ? inGetvalue : 30;
            }
        }
        #endregion

        #endregion

        #region 手机参数信息 内容编辑器信息 内容分页信息 附件设置信息  评论设置信息 广告参数

        static MobileConfigInfo mMobileConfigInfo;
        /// <summary>
        /// 手机参数信息
        /// 根据手机参数，决定生成图片时是否生成对应手机版图片
        /// </summary>
        public static MobileConfigInfo MobileConfig
        {
            get
            {
                if (mMobileConfigInfo == null)
                {
                    mMobileConfigInfo = Get_SaveClass<MobileConfigInfo>(Common.Util.GetMapPath(SystemConst.ConfigRootName + SystemConst.SystemParam_MobileFileName));
                }

                return mMobileConfigInfo;
            }
        }

        static List<DDLBindInfo> mContentEditors;
        /// <summary>
        /// 内容编辑器信息
        /// </summary>
        public static List<DDLBindInfo> ContentEditors
        {
            get
            {

                if (mContentEditors == null)
                {
                    mContentEditors = GetClass<List<DDLBindInfo>>(Common.Util.GetMapPath(SystemConst.ConfigRootName + SystemConst.SystemVar_ContentEditorFileName));

                    if (mContentEditors == null)
                    {
                        List<DDLBindInfo> oDDLBindInfos = new List<DDLBindInfo>();

                        oDDLBindInfos.Add(new DDLBindInfo()
                        {
                            VarKey = "default_editor",
                            VarName = "default_editor",
                            VarType = "text",
                            VarValue = "news_editor"
                        });
                        oDDLBindInfos.Add(new DDLBindInfo()
                        {
                            VarKey = "html_editor",
                            VarName = "html_editor",
                            VarType = "text",
                            VarValue = "html_editor"
                        });
                        oDDLBindInfos.Add(new DDLBindInfo()
                        {
                            VarKey = "xheditor",
                            VarName = "xheditor",
                            VarType = "text",
                            VarValue = "xheditor"
                        });

                        SaveClassToFile<List<DDLBindInfo>>(oDDLBindInfos, Common.Util.GetMapPath(SystemConst.ConfigRootName + SystemConst.SystemVar_ContentEditorFileName));

                        mContentEditors = oDDLBindInfos;

                    }
                }

                return mContentEditors;
            }
        }

        static List<DDLBindInfo> mContentPagers;
        /// <summary>
        /// 内容分页信息
        /// </summary>
        public static List<DDLBindInfo> ContentPagers
        {
            get
            {

                if (mContentPagers == null)
                {
                    mContentPagers = GetClass<List<DDLBindInfo>>(Common.Util.GetMapPath(SystemConst.ConfigRootName + SystemConst.SystemVar_ContentPagerFileName));

                    if (mContentPagers == null)
                    {
                        List<DDLBindInfo> oDDLBindInfos = new List<DDLBindInfo>();

                        oDDLBindInfos.Add(new DDLBindInfo()
                        {
                            VarKey = "default",
                            VarName = "default",
                            VarType = "default",
                            VarValue = "text"
                        });

                        SaveClassToFile<List<DDLBindInfo>>(oDDLBindInfos, Common.Util.GetMapPath(SystemConst.ConfigRootName + SystemConst.SystemVar_ContentPagerFileName));

                        mContentPagers = oDDLBindInfos;

                    }
                }

                return mContentPagers;
            }
        }

        static AttachmentSettingInfo mAttachmentSettingInfo;
        /// <summary>
        ///  附件设置信息
        /// </summary>
        public static AttachmentSettingInfo AttachmentSetting
        {
            get
            {
                if (mAttachmentSettingInfo == null)
                {
                    mAttachmentSettingInfo = Get_SaveClass<AttachmentSettingInfo>(Common.Util.GetMapPath(SystemConst.ConfigRootName + SystemConst.SystemParam_AttachmentFileName));
                }
                return mAttachmentSettingInfo;
            }
            set
            {
                mAttachmentSettingInfo = value;
                SaveClassToFile<AttachmentSettingInfo>(value, Common.Util.GetMapPath(SystemConst.ConfigRootName + SystemConst.SystemParam_AttachmentFileName));
            }
        }

        static RecommentConfigInfo mRecommentConfigInfo;
        /// <summary>
        ///  评论设置信息
        /// </summary>
        public static RecommentConfigInfo RecommentConfigerInfo
        {
            get
            {
                if (mRecommentConfigInfo == null)
                {
                    mRecommentConfigInfo = Get_SaveClass<RecommentConfigInfo>(Common.Util.GetMapPath(SystemConst.ConfigRootName + SystemConst.SystemVar_RecommentConfigFileName));
                }

                return mRecommentConfigInfo;

            }
            set
            {
                mRecommentConfigInfo = value;
                SaveClassToFile<RecommentConfigInfo>(value, Common.Util.GetMapPath(SystemConst.ConfigRootName + SystemConst.SystemVar_RecommentConfigFileName));
            }
        }

        /* 广告参数信息  */
        static AdvConfigInfo mAdvConfigInfo;
        /// <summary>
        /// 当前系统的广告参数信息
        /// </summary>
        public static AdvConfigInfo AdvertisementConfigInfo
        {
            get
            {

                if (mAdvConfigInfo == null)
                {
                    mAdvConfigInfo = Get_SaveClass<AdvConfigInfo>(Common.Util.GetMapPath(SystemConst.ConfigRootName + SystemConst.SystemVar_AdvConfigFileName));
                }

                return mAdvConfigInfo;

            }
            set
            {
                mAdvConfigInfo = value;
                SaveClassToFile<AdvConfigInfo>(value, Common.Util.GetMapPath(SystemConst.ConfigRootName + SystemConst.SystemVar_AdvConfigFileName));
            }
        }

        #endregion

        #region 设置参数所用到的方法
        static object _lock = new object();

        /// <summary>
        /// 获取类 从文件里
        /// </summary>
        /// <typeparam name="ClassTyle"></typeparam>
        /// <param name="strFileName"></param>
        /// <returns></returns>
        static ClassTyle GetClass<ClassTyle>(string strFileName) where ClassTyle : class  , new()
        {
            //get
            return SystemConfigHelper<ClassTyle>.Get(strFileName);
        }

        /// <summary>
        /// 保存初始配置信息
        /// </summary>
        /// <typeparam name="ClassTyle"></typeparam>
        /// <param name="oClassTyle"></param>
        /// <param name="strFileName"></param>
        static ClassTyle SaveNewClass<ClassTyle>(string strFileName) where ClassTyle : class  , new()
        {
            ClassTyle oClassTyle = new ClassTyle();

            SystemConfigHelper<ClassTyle>.Save(oClassTyle, strFileName);

            return oClassTyle;
        }

        /// <summary>
        /// 保存配置信息至文件
        /// </summary>
        /// <typeparam name="ClassTyle"></typeparam>
        /// <param name="oClassTyle"></param>
        /// <param name="strFileName"></param>
        static void SaveClassToFile<ClassTyle>(ClassTyle oClassTyle, string strFileName) where ClassTyle : class  , new()
        {
            SystemConfigHelper<ClassTyle>.Save(oClassTyle, strFileName);
        }

        /// <summary>
        /// 获取配置信息，如果配置信息没有，则保存初始的配置信息
        /// </summary>
        /// <typeparam name="ClassTyle"></typeparam>
        /// <param name="strFileName"></param>
        static ClassTyle Get_SaveClass<ClassTyle>(string strFileName) where ClassTyle : class  , new()
        {
            //get
            ClassTyle oClassTyle = GetClass<ClassTyle>(strFileName);

            //save
            if (oClassTyle == null)
            {
                oClassTyle = SaveNewClass<ClassTyle>(strFileName);
            }

            return oClassTyle;
        }
        #endregion
    }

    /// <summary>
    /// 系统配置帮助操作类
    /// </summary>
    /// <typeparam name="ClassType"></typeparam>
    internal static class SystemConfigHelper<ClassType> where ClassType : class
    {
        /// <summary>
        /// 保存信息至文件里
        /// </summary>
        /// <param name="oClassType"></param>
        /// <param name="strFileName"></param>
        /// <returns></returns>
        public static bool Save(ClassType oClassType, string strFileName)
        {
            return SerializationHelper.Save(oClassType, strFileName);
        }

        public static ClassType Get(string strFileName)
        {

            if (FileUtil.IsExist(strFileName))
            {
                return SerializationHelper.Load(typeof(ClassType), strFileName) as ClassType;
            }
            else
                return null;
        }
    }

}